package com.xzt.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzt.bookstore.dto.CartAddRequest;
import com.xzt.bookstore.dto.CartItemDTO;
import com.xzt.bookstore.entity.Book;
import com.xzt.bookstore.entity.Cart;
import com.xzt.bookstore.mapper.CartMapper;
import com.xzt.bookstore.service.BookService;
import com.xzt.bookstore.service.CartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车服务实现类
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    
    private final BookService bookService;
    
    public CartServiceImpl(BookService bookService) {
        this.bookService = bookService;
    }
    
    @Override
    @Transactional
    public Cart addToCart(Long userId, CartAddRequest request) {
        // 检查图书是否存在
        Book book = bookService.getById(request.getBookId());
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        
        // 检查图书是否在售
        if (book.getStatus() == 0) {
            throw new RuntimeException("图书已下架，无法添加到购物车");
        }
        
        // 检查库存
        if (book.getStock() < request.getQuantity()) {
            throw new RuntimeException("库存不足，当前库存：" + book.getStock());
        }
        
        // 查询购物车中是否已存在该商品
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .eq(Cart::getBookId, request.getBookId());
        Cart existingCart = this.getOne(wrapper);
        
        if (existingCart != null) {
            // 如果已存在，更新数量
            int newQuantity = existingCart.getQuantity() + request.getQuantity();
            if (book.getStock() < newQuantity) {
                throw new RuntimeException("库存不足，当前库存：" + book.getStock() + "，购物车已有：" + existingCart.getQuantity());
            }
            existingCart.setQuantity(newQuantity);
            this.updateById(existingCart);
            return existingCart;
        } else {
            // 如果不存在，创建新记录
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setBookId(request.getBookId());
            cart.setQuantity(request.getQuantity());
            this.save(cart);
            return cart;
        }
    }
    
    @Override
    public List<CartItemDTO> getCartList(Long userId) {
        // 查询用户的购物车
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .orderByDesc(Cart::getCreateTime);
        List<Cart> cartList = this.list(wrapper);
        
        // 转换为DTO并填充图书信息
        return cartList.stream().map(cart -> {
            Book book = bookService.getById(cart.getBookId());
            if (book == null) {
                return null; // 如果图书不存在，返回null，后续过滤掉
            }
            
            CartItemDTO dto = new CartItemDTO();
            dto.setCartId(cart.getId());
            dto.setBookId(book.getId());
            dto.setBookName(book.getName());
            dto.setAuthor(book.getAuthor());
            dto.setPrice(book.getPrice());
            dto.setQuantity(cart.getQuantity());
            dto.setSubtotal(book.getPrice().multiply(BigDecimal.valueOf(cart.getQuantity())));
            dto.setStock(book.getStock());
            dto.setCreateTime(cart.getCreateTime());
            return dto;
        }).filter(item -> item != null).collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public Cart updateQuantity(Long userId, Long cartId, Integer quantity) {
        // 查询购物车项
        Cart cart = this.getById(cartId);
        if (cart == null) {
            throw new RuntimeException("购物车项不存在");
        }
        
        // 验证是否为当前用户的购物车
        if (!cart.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作该购物车项");
        }
        
        // 检查数量
        if (quantity <= 0) {
            throw new RuntimeException("数量必须大于0");
        }
        
        // 检查库存
        Book book = bookService.getById(cart.getBookId());
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        if (book.getStock() < quantity) {
            throw new RuntimeException("库存不足，当前库存：" + book.getStock());
        }
        
        // 更新数量
        cart.setQuantity(quantity);
        this.updateById(cart);
        return cart;
    }
    
    @Override
    @Transactional
    public void removeFromCart(Long userId, Long cartId) {
        // 查询购物车项
        Cart cart = this.getById(cartId);
        if (cart == null) {
            throw new RuntimeException("购物车项不存在");
        }
        
        // 验证是否为当前用户的购物车
        if (!cart.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作该购物车项");
        }
        
        // 删除
        this.removeById(cartId);
    }
    
    @Override
    @Transactional
    public void clearCart(Long userId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId);
        this.remove(wrapper);
    }
}

